import {
  CanActivate,
  ExecutionContext,
  HttpStatus,
  Injectable,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { Request } from 'express';
import { JwtService } from '@nestjs/jwt';
import { TokenExpiredError, JsonWebTokenError } from '@nestjs/jwt';

import { throwHttpException } from '@/utils/nesjUtils';
import { ErrCode } from '@/types/globalType';
@Injectable()
export class TokenGuard implements CanActivate {
  constructor(private jwtService: JwtService) {}
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const request: Request = context.switchToHttp().getRequest();
    const token = request.headers.authorization;
    console.log('验证token执行', token);
    if (!token.split(' ')[1]) {
      throwHttpException(
        {
          errCode: ErrCode.TokenError,
          errMsg: '请检查参数是否正确！必填项: token',
          errStack: '',
        },
        HttpStatus.UNAUTHORIZED,
      );
    }
    try {
      this.jwtService.verify(token.split(' ')[1], {
        secret: 'daidaigou',
      });
    } catch (error) {
      // throw new HttpException('token失效', 401);
      console.log(error);
      if (error instanceof TokenExpiredError) {
        throwHttpException(
          {
            errCode: ErrCode.TokenError,
            errMsg: 'token 已过期！',
            errStack: '',
          },
          HttpStatus.UNAUTHORIZED,
        ); // 处理过期错误
      } else if (error instanceof JsonWebTokenError) {
        throwHttpException(
          {
            errCode: ErrCode.TokenError,
            errMsg: 'token 无效！',
            errStack: '',
          },
          HttpStatus.UNAUTHORIZED,
        );
        // 处理无效错误
      } else {
        throwHttpException(
          {
            errCode: ErrCode.TokenError,
            errMsg: 'token 其他错误！',
            errStack: '',
          },
          HttpStatus.UNAUTHORIZED,
        ); // 处理其他错误
      }
    }

    return true;
  }
}
